package cn.piesat.util.exception;

import cn.piesat.util.ResponseWrapperUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 参数校验异常统一处理
 *
 * @author xhl
 */
@RestControllerAdvice
public class ParamExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String validBodyException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return ResponseWrapperUtil.executeCustomTips("false",fieldError.getDefaultMessage());
            }
        }
        return ResponseWrapperUtil.executeCodeException();
    }

}
